let gulp = require('gulp')
let cssnano = require('gulp-cssnano')
let rename = require('gulp-rename') //重命名
let uglify = require('gulp-uglify') // 丑化
let concat = require('gulp-concat') // 合并
let imagemin = require('gulp-imagemin') // 压缩图片
let cache = require('gulp-cache') // 缓存已经处理过的文件
let sass = require('gulp-sass') // 缓存已经处理过的文件
let rev = require('gulp-rev')
let cssmin = require('gulp-cssmin')
let connect = require('gulp-connect');
const browserSync = require('browser-sync').create()
let reload = browserSync.reload;
let path = {
    'html': './templates/**/',
    'css': './src/css/',
    'script': './src/script/',
    'images': './src/images/',
    'dist_css': './dist/css/',
    'dist_script': './dist/script/',
    'dist_images': './dist/images/',
}

gulp.task('my_sass', () => {
    return gulp.src(path.css + '*.scss')
        .pipe(sass({style: 'expanded'}).on('error', sass.logError))
        .pipe(cssmin())
        .pipe(rename({'suffix': '.min'}))
        .pipe(gulp.dest(path.dist_css).on('error', function (error) {
            console.log(error)
        }))
        .pipe(connect.reload())
})

gulp.task('my_script', function () {
    return gulp.src(path.script + '*.js')
        .pipe(concat('index.js'))
        .pipe(uglify({
            'toplevel': true,
            'compress': {
                'drop_console': true
            }
        }))
        .pipe(rename({'suffix': '.min'}))
        .pipe(gulp.dest(path.dist_script))
        .pipe(browserSync.stream())
})

gulp.task('my_image', function () {
    return gulp.src(path.images + '*.*')
        .pipe(imagemin([
            imagemin.gifsicle({interlaced: true}),
            imagemin.optipng({optimizationLevel: 5})
        ]).on('error', function (error) {
            console.log(error)
        }))
        .pipe(gulp.dest(path.dist_images))
        .pipe(browserSync.stream())
})

gulp.task('bs', function () {
    return browserSync.init({
        'server': {
            baseDir: './',
            index: "./templates/news/index.html",
            keepOpen: false,
            autoplay: false,
        },
        reloadOnRestart: false,
        open: false
    })
})

gulp.task('watch', function () {
    gulp.watch(path.css + '*.css', gulp.series('my_sass'))
    gulp.watch(path.script + '*.js', gulp.series('my_script'), reload)
    gulp.watch(path.images + '*.*', gulp.series('my_image'))
    gulp.watch(path.html + '*.html', reload)
})

gulp.task('default', gulp.parallel(['bs', 'watch']))
